<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Services\AliSmsService;
use Illuminate\Http\Request;
use App\Models\SmsLog;
use Mrgoon\AliSms\AliSms;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Qiniu\Storage\UploadManager;

class QiniuController extends Controller
{
    public function upload(Request $request)
    {
        $file = $request->file('file');

        if ($file->isValid()) {
            $path = $file->getRealPath();
            $extension = $file->getClientOriginalExtension();
            $fileName = md5($path) . '.' . $extension;

            // 从服务容器解析配置
            $qiniuConfig = app('qiniu');
            $auth = $qiniuConfig['auth'];
            $bucket = $qiniuConfig['bucket'];

            // 生成上传Token
            $token = $auth->uploadToken($bucket);

            // 初始化 UploadManager 对象并进行文件上传
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $fileName, $path);

            if ($err !== null) {
//                return response()->json(['success' => false, 'msg' => $err->getMessage()]);
                return $this->failure($err);
            } else {
                // 返回文件在七牛云中的地址
                return $this->success($qiniuConfig['domain'] . '/' . $ret['key']);
//                return response()->json(['success' => true, 'file_path' => $qiniuConfig['domain'] . '/' . $ret['key']]);
            }
        }

        return response()->json(['success' => false]);
    }
}
